/**
 * 动态表单核心组件
 * @author SPY
 * @date 2020/01/15
 */

import React from 'react';
import PropTypes from 'prop-types';
import { Form, Row, Col } from 'antd';
import config from './_utils/config';
import convert from './_utils/convert';

// 定义页面级变量
const { Item } = Form;

@Form.create()
class DynamicForm extends React.Component {

    // 定义传入属性
    static propTypes = {
        fields: PropTypes.array.isRequired,  // 需要渲染出的表单列表
        // onSubmit: PropTypes.func.isRequired,
    }

    // 定义传入属性的默认值
    static defaultProps = {
    }

    componentDidMount() {
        const { getForm, form } = this.props;
        if (typeof getForm === 'function') getForm(form);
    }

    // 渲染表单项函数
    renderFormItem = (item, getFieldDecorator) => (
        <Col key={item.label} xs={24} sm={item.span > 12 ? item.span : 12} md={item.span || 8}>
            <Item key={item.label} label={item.label}>
                {getFieldDecorator(item.field, config(item))(convert(item))}
            </Item>
        </Col>
    )

    // 提交表单函数
    handleSubmit = (e) => {
        typeof e === 'object' && e.preventDefault();
        const { onSubmit, form } = this.props;
        form.validateFields((err, values) => {
            if (err) return;
            if (typeof onSubmit === 'function') onSubmit(values);
        });
    }

    // 重置
    handleReset = () => {
        const { form } = this.props;
        form.resetFields();
    }

    render() {
        const {
            fields,
            form: { getFieldDecorator },
            layout,
        } = this.props;

        return (
            <Form
                // onSubmit={this.handleSubmit}
                layout={layout}
            >
                <Row gutter={24}>
                    {fields.map(item => this.renderFormItem(item, getFieldDecorator))}
                </Row>
                {/* <Row type='flex' justify='center'>
                    <Col span={24}>
                        <Item style={{ textAlign: 'center' }}>
                            <Button onClick={this.handleReset} style={{ marginRight: '1%' }} >重置</Button>
                            <Button type='primary' htmlType='submit' >提交</Button>
                        </Item>
                    </Col>
                </Row> */}
            </Form>
        );
    }
}

export default DynamicForm;